import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { STChange, STColumnTag, STComponent } from '@delon/abc/st';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { UserEditComponent } from './edit/user-edit.component';
import { UserService } from './user.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from "ng-zorro-antd/modal";


const tag: STColumnTag = {
  0: {text: '禁用', color: 'red'},
  1: {text: '启用', color: 'green'},

};

@Component({
  selector: 'app-user-list',
  templateUrl: './user-list.component.html',
  styles: []
})
export class UserListComponent implements OnInit {

  @ViewChild('st', {static: false}) comp: STComponent;

  constructor(private http: _HttpClient,
              private msgSrv: NzMessageService,
              private modal: NzModalService,
              private cdr: ChangeDetectorRef,
              private userService: UserService,
              ) {
  }

  @ViewChild('userEditComponent', {static: false})
  public userEditComponent: UserEditComponent;

  url = 'api/sys-user/page-list';

  total = 1;
  size = 10;
  page = 0;

  loading = false;

  public params: any = {};
  users = [];

  ngOnInit(): void {
    this.loadUserList();
  }

  loadUserList() {

    this.loading = true;

    this.userService.findPage({'size': this.size, 'page': this.page}).subscribe((res) => {
      this.loading = false;
      if (res.code === 1) {
        this.users = res.data.content;
      } else {
        this.msgSrv.error(res.message);
      }
    });
  }

  change(e: STChange): void {
    console.log(e);
  }

  deleteCheck() {
    let selectedNode = this.comp._data.filter(item => item.checked);
    console.log(selectedNode);

    let idArr = selectedNode.map(function(item) {
      return item.id;
    });

    this.userService.deleteBatch(idArr).subscribe((res) => {
      if (res.code === 1) {
        this.comp.reload();
        this.msgSrv.success('删除完成');
      } else {
        this.msgSrv.error(res.message);
      }
    });

  }

  delete(id) {

    this.modal.confirm({
      nzTitle: '确定删除这个菜单吗?',
      nzOkText: 'Yes',
      nzOkType: 'danger',
      nzOnOk: () => {
        this.userService.delete(id).subscribe((res) => {
          if (res.code === 1) {
            this.msgSrv.success('删除完成');
            this.loadUserList();
          } else {
            this.msgSrv.error(res.message);
          }
        });
      },
      nzCancelText: 'No',
      nzOnCancel: () => console.log('Cancel')
    });
  }

  cancel() {
    this.msgSrv.success('已取消');
  }

  openEdit(record ?: any): void {
    console.log(record);
    this.userEditComponent.edit(record);

  }

  onSmt() {
    this.loadUserList();
  }

  _onReuseInit() {
    this.loadUserList();
  }
}
